package com.by.rpc.server;

import com.by.rpc.RpcApplication;
import com.by.rpc.model.RpcRequest;
import com.by.rpc.model.RpcResponse;
import com.by.rpc.registry.LocalRegistry;
import com.by.rpc.serializer.Serializer;
import com.by.rpc.serializer.SerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author lzh
 */
public class HttpServerHandler implements Handler<HttpServerRequest> {

    @Override
    public void handle(HttpServerRequest request) {
        // 指定序列化器
        final Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

        // 异步处理请求
        request.bodyHandler(body -> {
            // 获取请求的字节流
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            // 反序列化为请求对象
            try {
                rpcRequest = serializer.deserialize(bytes, RpcRequest.class);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 构造响应对象
            RpcResponse rpcResponse = new RpcResponse();
            // 如果请求为空直接返回
            if (rpcRequest == null) {
                rpcResponse.setMessage("rpcRequest is null");
                doResponse(request, rpcResponse, serializer);
                return;
            }

            // 调用服务实现类获取结果
            try {
                // 反射调用
                Class<?> implClassType = LocalRegistry.get(rpcRequest.getServiceName());
                Method method = implClassType.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object result = method.invoke(implClassType.newInstance(), rpcRequest.getArgs());
                // 封装返回结果
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            } catch (Exception e) {
                e.printStackTrace();
                rpcResponse.setMessage(e.getMessage());
                rpcResponse.setException(e);
            }
            // 响应
            doResponse(request, rpcResponse, serializer);
        });
    }

    /**
     * 处理请求返回响应
     *
     * @param request     http请求
     * @param rpcResponse 通用响应对象
     * @param serializer  序列化器
     */
    public void doResponse(HttpServerRequest request, RpcResponse rpcResponse, Serializer serializer) {
        // 获取响应对象
        HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");
        // 序列化响应对象
        try {
            byte[] bytes = serializer.serialize(rpcResponse);
            response.end(Buffer.buffer(bytes));
        } catch (IOException e) {
            e.printStackTrace();
            response.end(Buffer.buffer());
        }
    }
}
